package main.java.com.chankudo.network;

import java.io.BufferedReader;
import java.io.InputStream;
import java.io.InputStreamReader;
import java.net.HttpURLConnection;
import java.net.URL;
import java.util.List;
import java.util.Map;
import java.util.Map.Entry;

public class TestHttpClient {
    public static void main(String[] args) throws Exception {
        URL url = new URL("https://www.liaoxuefeng.com/wiki/1252599548343744/1319099982413858");
        HttpURLConnection httpConnection = (HttpURLConnection) url.openConnection();

        //设置请求方法
        httpConnection.setRequestMethod("GET");
        //是否用cache
        httpConnection.setUseCaches(false);
        //设置超时
        httpConnection.setReadTimeout(5000);

        /*
        设置http头
        */
        //Accept：表示客户端能处理的HTTP响应格式，*/*表示任意格式，text/*表示任意文本，image/png表示PNG格式的图片
        httpConnection.setRequestProperty("Accept", "*/*");
        //User-Agent：表示客户端自身标识信息，不同的浏览器有不同的标识，服务器依靠User-Agent判断客户端类型是IE还是Chrome，是Firefox还是一个Python爬虫；
        httpConnection.setRequestProperty("User-Agent", "Mozilla/5.0 (compatible; MSIE 11; Windows NT 5.1)");
        
        // 连接
        httpConnection.connect();

        // 返回码不为 200 就退出
        if( httpConnection.getResponseCode() != 200){
            System.out.println("response error: code=" + httpConnection.getResponseCode());
            return;
        }
        
        // 获取返回报文头
        Map<String, List<String>> fieldMap = httpConnection.getHeaderFields();
        for(Entry<String, List<String>> entrySet : fieldMap.entrySet()){
            System.out.println("head property: " + entrySet.getKey());
            for(String value : entrySet.getValue()){
                System.out.print("value: "+value+" ");
            }
            System.out.println(); 
        }

        InputStream inputStream = httpConnection.getInputStream();
        BufferedReader bufferedReader = new BufferedReader(new InputStreamReader(inputStream, "UTF-8"));
        String line = bufferedReader.readLine();
        while(!line.isEmpty()){
            System.out.println(line);
            line = bufferedReader.readLine();
        }
        bufferedReader.close();
        httpConnection.disconnect();
    }
    
}
